package com.fzkj.bio;

import java.io.*;
import java.util.Arrays;

/**
 * @DESCRIPTION: TODO 安全关闭流
 * @AUTHOR: AnotherOne
 * @DATE: 2021/9/29 17:07
 */
public class StreamClose {

    public static void main(String[] args) {
        FileInputStream fis = null;
        PrintWriter pw = null;
        try {
            fis = new FileInputStream("F:\\supermap\\超图账号.xlsx");
            pw = new PrintWriter("F:\\supermap\\超图账号.xlsx");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            safeColse(fis);
            safeColse(pw);
        }

        System.out.println("===============================");
        System.out.println("========验证在finally中关闭流，同时将流返回，这个流的状态，========");

        FileInputStream fis1 = fis();
        byte[] bytes = new byte[1024];
        try {
            System.out.println(fis1.available());
            fis1.read(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(Arrays.toString(bytes));
        System.out.println(status);
    }

    public static void safeColse(Closeable target){
        if (target != null){
            try {
                target.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static int status = 0;

    public static FileInputStream fis(){
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("F:\\supermap\\超图账号.xlsx");
            return returnFis(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                status = 10;
                System.out.println("流关闭了");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static FileInputStream returnFis(FileInputStream fis){
        System.out.println("返回流");
        status = 20;
        //        System.out.println(status);
        return fis;
    }
}
